//退出
document.querySelector('#logout').addEventListener('click', function () {
    localStorage.removeItem('token')
    location.href = '/login.html'
})


//把用户的信息渲染展示在页面上
const userName = JSON.parse(localStorage.getItem('token'))
// console.log(userName);
document.querySelector('#userName').innerHTML = userName.username
document.querySelectorAll('.avatar img').forEach(item => {
    item.src = userName.avatar ? userName.avatar : 'https://yanxuan-item.nosdn.127.net/8b27deb1670c53e67c42ca3e1ed6fd12.jpg'
})
const list = document.querySelector('.list')
//获取学生列表
getStudentList()
function getStudentList() {
    axios.get('/students')
        .then(({ data: { data } }) => {
            // console.log(data)
            list.innerHTML = data.map(({ id, name, age, gender, province, area, city, hope_salary, salary, group }) => {
                let genders = gender === 0 ? '男' : '女'
                return `
        <tr>
                      <td>${name}</td>
                      <td>${age}</td>
                      <td>${genders}</td>
                      <td>第${group}组</td>
                      <td>${hope_salary}</td>
                      <td>${salary}</td>
                      <td>${province}${city}${area}</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id=${id}></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id=${id}></i></a>
                      </td>
                    </tr>
        `}).join('')
            document.querySelector('.total').innerHTML = data.length
        })
}


//todo  事件委托删除修改
let editId
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)
const province = document.querySelector('[name=province]')
const cityObj = document.querySelector('[name=city]')
const areaObj = document.querySelector('[name=area]')
list.addEventListener('click', function (e) {
    // 删除
    if (e.target.className === 'bi bi-trash') {
        // console.log(55);
        const { id } = e.target.dataset
        // console.log(id);
        axios.delete(`/students/${id}`)
            .then(res => {
                // console.log(res)
                getStudentList()
                tip('删除成功')
                // console.log('删除成功');
            })
            .catch(err => {
                console.dir(err);
            })
    }

    // 学生信息修改
    if (e.target.className === 'bi bi-pen') {
        // console.log(66);
        modalBox.querySelector('.modal-title').innerHTML = '修改学员'
        const { id } = e.target.dataset
        editId = id
        axios.get(`/students/${id}`)
            .then(({ data: { data: student } }) => {
                // console.log(student)
                const nameData = document.querySelectorAll('form [name]')
                // console.log(nameData);
                nameData.forEach(item => {
                    if (item.name === 'gender') {
                        if (+item.value === student[item.name]) item.checked = true
                    } else {
                        item.value = student[item.name]
                    }
                })
                getCity()
                cityObj.value = student.city
                // console.log(student.city);
                getArea()
                areaObj.value = student.area
                // console.log(cityObj);
            })

        modal.show()
    }

})


//todo  添加学生
document.querySelector('#openModal').addEventListener('click', () => {
    modalBox.querySelector('form').reset()
    modalBox.querySelector('.modal-title').innerHTML = '添加学员'
    modalBox.dataset.id = 'add'
    modal.show()
})

// 获取省份

axios.get('/api/province')
    .then(({ data: { data } }) => {
        // console.log(data)
        const htmlStr = data.map(item => `
    <option value=${item}>--${item}--</option>
    `).join('')
        province.innerHTML = `<option value="">--省份--</option>${htmlStr}`
    })
    .catch(err => {
        console.error(err);
    })

// 获取城市
province.addEventListener('change', function () {
    areaObj.value = ''
    getCity()
})
function getCity() {
    axios.get('/api/city', { params: { pname: province.value } })
        .then(({ data: { data } }) => {
            // console.log(data)
            const htmlStr = data.map(item => `
    <option value=${item}>--${item}--</option>
    `).join('')
            cityObj.innerHTML = `<option value="1">--城市--</option>${htmlStr}`
        })
        .catch(err => {
            console.error(err);
        })
}

//获取地区
cityObj.addEventListener('change', function () {
    getArea()
})

function getArea() {
    axios.get('/api/area', {
        params: {
            pname: province.value,
            cname: cityObj.value
        }
    })
        .then(({ data: { data } }) => {
            // console.log(data)
            const htmlStr = data.map(item => `
    <option value=${item}>--${item}--</option>
    `).join('')
            areaObj.innerHTML = `<option value="">--地区--</option>${htmlStr}`
        })
        .catch(err => {
            console.error(err);
        })
}

// 获取表单数据添加
const form = document.querySelector('#form')
document.querySelector('#submit').addEventListener('click', function () {
    // 收集表单数据
    const data = serialize(form, { hash: true })
    // 处理格式（后台部分数据需要number格式）
    data.age = +data.age
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    data.gender = +data.gender
    data.group = +data.group
    // console.log(data);
    if (modalBox.dataset.id === 'add') {
        // 添加
        axios.post('/students', data)
            .then(res => {
                modal.hide()
                getStudentList()
                tip('添加成功')
                // console.log('添加成功');
            })
            .catch(err => {
                console.error(err);
                // console.log('失败');
            })
    } else {
        //修改
        // console.log(editId);
        axios.put(`/students/${editId}`, data)
            .then(res => {
                modal.hide()
                getStudentList()
                tip('修改成功')
                // console.log('添加成功');
            })
            .catch(err => {
                console.error(err);
                // console.log('失败');
            })
    }

})






